package handler

import (
	"github.com/gin-gonic/gin"
	"store-inv-mgmt/model"
	"strconv"
)

func AddShop(c *gin.Context) {
	shop_code := c.PostForm("shop_code")
	shop_name := c.PostForm("shop_name")
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	shop := model.Shop{
		ShopCode: shop_code,
		ShopName: shop_name,
		Rid:      rid,
	}
	err := model.DB.Create(&shop).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "添加成功"})
	return
}
func ShopList(c *gin.Context) {
	var shop []model.Shop
	err := model.DB.Find(&shop).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "查询失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": shop})
	return
}
func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{"code": 500, "msg": "数据库不能为空"})
		return
	}
	var user model.User
	err := model.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "查询失败"})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{"code": 500, "msg": "用户名不存在"})
		return
	}
	if user.Password != password {
		c.JSON(200, gin.H{"code": 500, "msg": "密码错误"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "登录成功"})
	return
}
func Update(c *gin.Context) {
	id := c.Query("id")
	shop_name := c.Query("shop_name")
	err := model.DB.Model(&model.Shop{}).Where("id=?", id).Update("shop_name", shop_name).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "修改失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "修改成功"})
	return
}
